package com.example.service;

import com.example.entity.Delivery;
import com.example.entity.Inbound;
import com.example.entity.Warehouse;
import com.example.exception.CustomerException;
import com.example.mapper.DeliveryMapper;
import com.example.mapper.InboundMapper;
import com.example.mapper.WarehouseMapper;
import com.example.utils.MapUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Service
public class InboundService {

    @Resource
    InboundMapper inboundMapper;
    @Resource
    WarehouseMapper warehouseMapper;
    @Resource
    DeliveryMapper deliveryMapper;
    @Resource
    MapUtils mapUtils;

    public void add(Inbound inbound) {
        // 添加入库表
        inboundMapper.insert(inbound);
        // 更改配送表上当前位置
        Warehouse warehouse = warehouseMapper.selectById( inbound.getWarehouseId());
        String address = warehouse.getAddress();
        try {
            Map<String,String> map = mapUtils.getLonAndLat(address);
            BigDecimal lng = new BigDecimal(map.get("lng"));
            BigDecimal lat = new BigDecimal(map.get("lat"));
            Delivery delivery = Delivery.builder()
                    .deliveryId(inbound.getDeliveryId())
                    .currentAddress(address)
                    .currentLongitude(lng)
                    .currentLatitude(lat)
                    .build();
            deliveryMapper.updateById(delivery);
        }catch (Exception e){
            throw new CustomerException("入库时更改当前位置异常");
        }
    }

    public void deleteById(Integer id) {
        inboundMapper.deleteById(id);
    }

    public void updateById(Inbound inbound) {
        inboundMapper.updateById(inbound);
    }

    public List<Inbound> selectAll() {
        return inboundMapper.selectAll();
    }

    public Inbound selectById(Integer id) {
        return inboundMapper.selectById(id);
    }

    public PageInfo<Inbound> selectPage(Integer pageNum, Integer pageSize) {
        //开启分页查询
        PageHelper.startPage(pageNum, pageSize);
        List<Inbound> list = inboundMapper.selectAll();
        return PageInfo.of(list);
    }
}
